//
//  NSObject+HDChatFmdbManager.m
//  app
//
//  Created by D on 15/5/21.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HDChatFmdbManager.h"
#import "SNFmdbManager.h"

@interface HDChatFmdbManager ()

@property (nonatomic,strong) JKHttpClient * jkHttp;
@property (nonatomic,strong) SNUniteUrl * uniteUrl;
@property (nonatomic,strong) FMDatabaseQueue * fmdbQueue;
@property (nonatomic,strong) SNFmdbManager * snFmdbManager;
@property (nonatomic,assign) int isRepeat;
@property (nonatomic,assign) int isChatContentRepeat;
@property (nonatomic,assign) BOOL includeChatList;
@property (nonatomic,assign) BOOL includeData;

@end

@implementation HDChatFmdbManager

+(HDChatFmdbManager *)shareManager
{
    AS_SINGLETON(HDChatFmdbManager, manager,{
        manager = [[HDChatFmdbManager alloc]init];
        manager.jkHttp = [[JKHttpClient alloc]init];
        manager.uniteUrl = [SNUniteUrl shareUniteUrl];
        manager.snFmdbManager = [SNFmdbManager shareManager];
//        HDAppDelegate * delegate = (HDAppDelegate*)[UIApplication sharedApplication].delegate;
//        manager.fmdbQueue  = delegate.fmdbQueue;

    })
    return manager;
}

-(void)loadShopContent:(HDChatProductResult*)result  Extends:(NSDictionary*)extends Product:(NSString*)product_id
{
    if ([self.jkHttp isRunning]) {
        return;
    }
    
    NSString * productUrl = [NSString stringWithFormat:@"%@?product_id=%@",self.uniteUrl.im_chatShopContentUrl,product_id];
    DLog(@"%@",productUrl);
    [self.jkHttp get:productUrl result:^(JKResponse *resp) {
        DLog(@"content = %@",resp.content);
        if (resp.OK) {
            result.success = YES;
            result.pushDic = extends;
            result.extends = resp.content;
        }else if (resp.failure){
            result.failure = YES;
        }
        [result invoke];
        
           }];
    


    

}


#pragma mark - 创建表
- (void)createFmdb
{
//    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
//        NSString * sql = @"create table if not exists ChatList(pmid TEXT PRIMARY KEY ,name TEXT ,face TEXT, lastTalk TEXT,time TEXT, uid TEXT,msgid TEXT,omit TEXT, omitid TEXT,delSign TEXT);";
//        BOOL ret2 = [db executeUpdate:sql];
//        if (ret2) {
//            DLog(@"创建ChatList表成功");
//        }
//        //[db close];
//    }];
//    //[self.fmdbQueue close];
    NSString * sql = [NSString stringWithFormat: @"create table if not exists ChatList_%@(uid TEXT PRIMARY KEY ,pmid TEXT,name TEXT ,face TEXT, lastTalk TEXT,time TEXT, ownerAddId TEXT,msgid TEXT,omit TEXT, omitid TEXT,delSign TEXT);",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
    
    [self.snFmdbManager createTableWithSql:sql];
}
#pragma mark - 聊天列表去重
-(int)isRepeatFromFmdbWithPmid:(NSString*)tempPmid  Msgid:(NSString*)tempMsgid
{
    NSMutableArray * arr1 = [NSMutableArray array];
    
    [self.snFmdbManager.fmdbQueue inDatabase:^(FMDatabase *db) {
        NSString * s = [NSString stringWithFormat:@"select * from sqlite_master where name  = 'ChatList_%@';",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
        FMResultSet * set_one = [db executeQuery:s];
        if ([set_one next]){
            NSString * sql = [NSString stringWithFormat: @"select * from ChatList_%@;",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
            FMResultSet * set = [db executeQuery:sql];
            while ([set next]) {
                NSString * pimd = [set  stringForColumn:@"pmid"];
                NSString * msgid = [set stringForColumn:@"msgid"];
              
                NSDictionary * dict = @{@"pmid":pimd,
                                        @"msgid":msgid};
                
                [arr1 addObject:dict];
            }
            [set close];
        }
        [set_one close];
        //[db close];
    }];
    //[self.fmdbQueue close];

    for (int i = 0; i < arr1.count;  i++) {
        NSString * pmid = [[arr1 objectAtIndex:i]objectForKey:@"pmid"];
        NSString * msgid = [[arr1 objectAtIndex:i]objectForKey:@"msgid"];
        if ([pmid isEqualToString:tempPmid]) {
            DLog(@"tempPmid = %@",tempPmid);
            if (tempMsgid.integerValue == (msgid.integerValue+1)) {
                //更新
                self.isRepeat = 1;
                return self.isRepeat;
            }else if (tempMsgid.integerValue > (msgid.integerValue+1)){
                //更新
                self.isRepeat = 2;
                return self.isRepeat;
            }else
            {
                self.isRepeat = 0;
                return self.isRepeat;
            }

        
        }else{
            //插入
            self.isRepeat = 3;
        }
    
    
    }

    
    return self.isRepeat;
}

#pragma mark - 聊天内容去重
-(int)isRepeatChatContentFromFmdbWithPeopleUid:(NSString*)fuid Msgid:(NSString*)tempMsgid
{
    NSMutableArray * arr1 = [NSMutableArray array];
    
    [self.snFmdbManager.fmdbQueue inDatabase:^(FMDatabase *db) {
        NSString * sql1 = [NSString stringWithFormat:@"select * from sqlite_master where name  = 'Chat_%@_%@';",fuid,[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
        FMResultSet * set_one = [db executeQuery:sql1];
        if ([set_one next]){
            NSString * sql = [NSString stringWithFormat:@"select * from Chat_%@_%@;",fuid,[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
            FMResultSet * set = [db executeQuery:sql];
            while ([set next]) {
            
                NSString * msgid = [set stringForColumn:@"msgid"];
                [arr1 addObject:msgid];
            }
            [set close];
        }
        [set_one close];
        //[db close];
    }];
    //[self.fmdbQueue close];
    
    for (int i = 0; i < arr1.count;  i++) {
        NSString * msgid = [arr1 objectAtIndex:i];
        if (msgid.length > 0) {
        
            if (tempMsgid.integerValue == (msgid.integerValue+1)) {
                //更新
                self.isChatContentRepeat = 1;
                return self.isChatContentRepeat;
            }else if (tempMsgid.integerValue > (msgid.integerValue+1)){
                //更新
                self.isChatContentRepeat = 2;
                return self.isChatContentRepeat;
            }else
            {
                self.isChatContentRepeat = 0;
                return self.isChatContentRepeat;
            }
            
            
        }else
        {
            //插入
            self.isChatContentRepeat = 3;
        }
        
        
    }
    
    
    return self.isChatContentRepeat;
}

#pragma mark - 保存插入
-(void)saveDataToDB:(NSArray *)array OwnerAddId:(NSString*)ownerAddId
{

    [self.snFmdbManager.fmdbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
       
        
        
        NSString * sql = [NSString stringWithFormat:@"insert into ChatList_%@(uid ,pmid,name,face, lastTalk,time, ownerAddId,msgid,omit, omitid,delSign) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
        
        if ([db executeUpdate:sql withArgumentsInArray:array]) {
            DLog(@"插入Chatlist表成功");
        }
        
    }];
   
    
    
}
#pragma mark - 更新数据
-(void)updata:(NSDictionary*)pushDic
{

    
    [self.snFmdbManager.fmdbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
       
        
        
        NSString * sql = [NSString stringWithFormat:@"UPDATE ChatList_%@ SET pmid = '%@', name = '%@',face = '%@',lastTalk = '%@',time = '%@',msgid = '%@',omit = '%@',omitid = '%@',delSign = '%@' WHERE uid = '%@' ",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"],[pushDic objectForKey:@"m"],[pushDic objectForKey:@"n"],[pushDic objectForKey:@"f"],[pushDic objectForKey:@"c"],[pushDic objectForKey:@"d"],[pushDic objectForKey:@"i"],[pushDic objectForKey:@"sign"],[pushDic objectForKey:@"i"],[pushDic objectForKey:@"delSign"],[pushDic objectForKey:@"u"]];
        if ([db executeUpdate:sql]) {
            DLog(@"更新Chatlist表成功");
        }
        
    }];
    
    
}
#pragma mark - 表是否存在
- (BOOL)fmdbIncludeChatList
{
    NSString * tablename = [NSString stringWithFormat:@"ChatList_%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
    return [self.snFmdbManager fmdbIncludetableWithTableName:tablename];
    
}
#pragma mark - 表中是否存有数据
- (BOOL)fmdbIncludeData
{

    NSString * tablename = [NSString stringWithFormat:@"ChatList_%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
    return [self.snFmdbManager fmdbIncludetableWithTableName:tablename];
    
}
#pragma mark - 创建回帖详情表
-(void)createTableWithReply
{
    

    NSString * sql = @"create table if not exists ChatReply(msgid TEXT PRIMARY KEY , title TEXT, uid TEXT,forum TEXT,card TEXT,content TEXT ,face TEXT,name TEXT,time TEXT, omit TEXT, omitid TEXT);" ;
    [self.snFmdbManager createTableWithSql:sql];
    
}
#pragma mark - 插入回帖详情表
-(void)saveToChatReplyDb:(NSArray*)array
{
    [self createTableWithReply];
    
//    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
//        NSString * sql = @"insert into ChatReply(msgid,title, uid,forum,card,content,face,name,time,omit,omitid) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
//        
//        if ([db executeUpdate:sql withArgumentsInArray:array]) {
////            DLog(@"保存成功到ChatReply表中");
//        }
//        //[db close];
//    }];
//    //[self.fmdbQueue close];
     NSString * sql = @"insert into ChatReply(msgid, title, uid, forum, card, content, face, name, time, omit, omitid) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
    [self.snFmdbManager performExecuteUpdateWithSql:sql withArguments:array];
    
}









#pragma mark - 创建聊天详情表
-(void)createTableWithPeople:(NSString*)uid
{

    NSString * sql = [NSString stringWithFormat:@"create table if not exists Chat_%@_%@(ownerAddId TEXT PRIMARY KEY ,time TEXT, content TEXT,fuid TEXT, uid TEXT,msgid TEXT,lastid TEXT,picture TEXT,omit TEXT, omitid TEXT,type TEXT,mtype TEXT,extends TEXT,flower TEXT ,red TEXT);",uid,[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]] ;
    [self.snFmdbManager createTableWithSql:sql];
    
    [self.snFmdbManager.fmdbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
       
        NSString * sql = [NSString stringWithFormat:@"create table if not exists Chat_%@_%@(ownerAddId TEXT PRIMARY KEY ,time TEXT, content TEXT,fuid TEXT, uid TEXT,msgid TEXT,lastid TEXT,picture TEXT,omit TEXT, omitid TEXT,type TEXT,mtype TEXT,extends TEXT,flower TEXT ,red TEXT);",uid,[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]] ;
        
        if ([db executeUpdate:sql]) {
            DLog(@"创建Chatuid表成功");
        }
        
    }];
    
    
}
#pragma mark - 聊天详情保存插入
-(void)saveDataToDbPeople:(NSArray*)array People:(NSString*)uid
{

    [self.snFmdbManager.fmdbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
       
        NSString * sql = [NSString stringWithFormat:@"insert into Chat_%@_%@(ownerAddId, time, content, fuid, uid, msgid, lastid, picture, omit, omitid, type, mtype, extends, flower, red) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);",uid,[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
        if ([db executeUpdate:sql withArgumentsInArray:array]) {
            DLog(@"插入chatuid表成功");
        }
        
    }];
    
}
#pragma mark - 聊天详情更新
-(void)updataToChatContent:(NSDictionary*)pushDic
{

    
    NSString * sql = [NSString stringWithFormat:@"UPDATE Chat_%@_%@ SET time = '%@', content = '%@',fuid = '%@',uid = '%@',msgid = '%@',lastid = '%@',omit = '%@',omitid = '%@' WHERE msgid = '%@' ",[pushDic objectForKey:@"u"],[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"],[pushDic objectForKey:@"d"],[pushDic objectForKey:@"c"],[pushDic objectForKey:@"fuid"],[pushDic objectForKey:@"u"],[pushDic objectForKey:@"i"],[pushDic objectForKey:@"l"],[pushDic objectForKey:@"sign"],[pushDic objectForKey:@"i"],[pushDic objectForKey:@"i"]];
    [self.snFmdbManager performExecuteUpdateWithSql:sql];
    
}


-(BOOL)fmdbIncludeChatPeople:(NSString*)uid
{

    NSString * tableName = [NSString stringWithFormat:@"Chat_%@_%@",uid,[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
   return  [self.snFmdbManager fmdbIncludetableWithTableName:tableName];
    
}

-(BOOL)fmdbInculdeContentDataWithPeople:(NSString *)uid
{

    NSString * tableName = [NSString stringWithFormat:@"Chat_%@_%@",uid,[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
   return  [self.snFmdbManager tabelIncludeDataWithTableName:tableName];
    
}


@end


